<template>
  <div>
    <!--面包屑-->
    <el-breadcrumb separator="/" style="font-size: 12px;padding-bottom: 10px;padding-left: 10px">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
    </el-breadcrumb>
    <!--用户列表卡片-->
    <el-card class="box-card">
      <el-row :gutter="15">
        <el-col :span="6" :xs="24">
          <el-card class="box-card">
            <div slot="header">
              <span>个人信息</span>
            </div>
            <div class="text-center">
              <div class="user-info-head" @click="imagecropperShow=true">
                <img :src="user.avatar"
                     title="点击上传头像"
                     class="img-circle img-lg" alt=""/>
              </div>
            </div>
            <el-form :model="user" size="medium" label-width="100px">
              <el-form-item>
                <image-cropper v-show="imagecropperShow"
                                :width="300" :height="300"
                                :key="imagecropperKey"
                                :url="'/uploadImgFile'"
                                field = "file"
                                @close = "closeImage"
                                @crop-upload-success="cropSuccess"
                
                />
              </el-form-item>
            </el-form>
            <div>
              <ul class="list-group list-group-striped">
                <li class="list-group-item">
                  <svg-icon icon-class="user"/>
                  用户名称
                  <div class="pull-right">{{ user.username }}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="phone"/>
                  手机号码
                  <div class="pull-right">{{ user.phoneNumber }}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="email"/>
                  用户邮箱
                  <div class="pull-right">{{ user.email }}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="tree"/>
                  所属部门
                  <div class="pull-right">{{ user.name }}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="peoples"/>
                  所属角色
                  <div class="pull-right">{{ user.roles[0].roleName}}</div>
                </li>
                <li class="list-group-item">
                  <svg-icon icon-class="date"/>
                  创建日期
                  <div class="pull-right">{{ user.createTime }}</div>
                </li>
              </ul>
            </div>
          </el-card>
        </el-col>

        <el-col :span="10">
          <el-card class="box-card">

            <div slot="header">
              <span>基本资料</span>
            </div>
            <el-tabs v-model="activeTab">
              <el-tab-pane label="基本资料" name="userInfo">
                <el-form ref="elForm" :model="user" :rules="rules" size="medium" label-width="100px">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="user.nickname" placeholder="请输入昵称" clearable="" :style="{width: '100%'}">
                    </el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="user.email" placeholder="请输入邮箱" clearable="" :style="{width: '100%'}">
                    </el-input>
                  </el-form-item>

                  <el-form-item label="手机号" prop="phoneNumber">
                    <el-input v-model="user.phoneNumber" placeholder="请输入手机号" clearable=""
                              :style="{width: '100%'}"></el-input>
                  </el-form-item>

                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="user.sex" size="medium">
                      <el-radio v-for="(item, index) in sexOptions" :key="index" :label="item.value"
                                :disabled="item.disabled">{{item.label}}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <el-form-item label="生日" prop="birth">
                    <el-date-picker v-model="user.birth" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                    :style="{width: '100%'}" placeholder="请选择生日" clearable=""></el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="danger" size="mini" @click="close">关闭</el-button>
                    <el-button type="primary" size="mini" @click="handelConfirm">确认修改</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="修改密码" name="resetPwd">
                <el-form ref="form" :model="userPassword" :rules="rules" label-width="80px">
                  <el-form-item label="旧密码" prop="oldPassword">
                    <el-input v-model="userPassword.oldPassword" placeholder="请输入旧密码" type="password"/>
                  </el-form-item>
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="userPassword.newPassword" placeholder="请输入新密码" type="password"/>
                  </el-form-item>
                  <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input v-model="userPassword.confirmPassword" placeholder="请确认密码" type="password"/>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="danger" size="mini" @click="close">关闭</el-button>
                    <el-button type="primary" size="mini" @click="handlePassWordConfirm">确认修改</el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>

            </el-tabs>
          </el-card>
        </el-col>

      </el-row>
    </el-card>
  </div>
</template>
<script>
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
import SvgIcon from '@/components/SvgIcon'

import { loginInfo} from '@/api/system/login'
import {deleteImgFile} from '@/api/oss'
import {deleteFileByUrl,saveFile} from '@/api/system/file'
import {update,updateUserPassWord } from '@/api/users'

export default {
  inheritAttrs: false,
  components:{
    ImageCropper,PanThumb,SvgIcon
  },
  created(){
    this.opOpen()
  },
  data(){
    const equalToPassword = (rule, value, callback) => {
        if (this.userPassword.newPassword !== value) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }

    return{
      oldImage:'',
      user:{},
      //控制弹出框显示隐藏
      imagecropperShow: false,
      imagecropperKey: 0,
      oldImage: '',
      activeTab: 'userInfo',
      oldUser: {},
      userPassword: {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined
      },
      file:{
        url : null,
        type: '',
        fileName: undefined,
        size: undefined,
      },
      rules: {
        username: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }],
        nickname: [{
          required: true,
          message: '请输入昵称',
          trigger: 'blur'
        }],
        sex: [{
          required: true,
          message: '性别不能为空',
          trigger: 'change'
        }],
        email: [
          {
            required: true,
            message: '邮箱地址不能为空',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '\'请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phoneNumber: [
          {
            required: true,
            message: '手机号码不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        birth: [{
          required: true,
          message: '请选择生日',
          trigger: 'change'
        }],
        oldPassword: [{
          required: true,
          message: '旧密码不能为空',
          trigger: 'blur'
        }],
        newPassword: [{
          required: true,
          message: '新密码不能为空',
          trigger: 'blur'
        },
          {
            min: 6,
            max: 20,
            message: '长度在 6 到 20 个字符',
            trigger: 'blur'
          }
        ],
        confirmPassword: [
          {
            required: true,
            message: '确认密码不能为空',
            trigger: 'blur'
          },
          {
            required: true,
            validator: equalToPassword,
            trigger: 'blur'
          }
        ]
      },
      sexOptions: [{
          'label': '男',
          'value': 0
        }, {
          'label': '女',
          'value': 1
        }, {
          'label': '保密',
          'value': 2
        }],
    }
  },
  methods:{
  async reloadUserInfo(){
    const  { data : res  } = await loginInfo()
    localStorage.removeItem('userInfo')
    this.$store.commit('setUserInfo',res.user)
    location.reload()
  },
  opOpen(){
    this.user = JSON.parse(localStorage.getItem('userInfo'))
    console.log(this.user)
    this.oldImage = this.user.avatar
  },
  cropSuccess(data){
    console.log(data)
    this.imagecropperShow = false
    //上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
    this.imagecropperKey = this.imagecropperKey + 1
    //保存上传的头象
    this.user.avatar = this.image = data.url
    this.file = data.file
    this.deleteAvatar(this.oldImage)
    this.deleteFileInMysql(this.oldImage)
    this.addFile()
    this.updateUser()
  },
  async deleteAvatar(oldImg){
    await deleteImgFile(oldImg)
  },
  async deleteFileInMysql(oldImg){
    await deleteFileByUrl(oldImg)
  },
  async addFile(){
    await saveFile(this.file)
  },
  closeImage(){
    this.imagecropperShow = false
    //上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
    this.imagecropperKey = this.imagecropperKey + 1
  },
  async updateUser(){
    const res = await update(this.user.id,this.user)
    console.log(res)
    if(res.code === 200){
      this.$notify.success({
        title:'操作成功',
        message: '信息修改',
      })
      this.reloadUserInfo()
    }else{
      return this.$message.error('修改失败:',res.message);
    }
  },
  //关闭
  close(){
    //清空当地弹窗数据
    this.user = {}
    this.oldImage = ''
    this.$refs['elForm'].resetFields()
    this.$refs['form'].resetFields()
    this.$router.back()
  },
  //修改基本资料
  handelConfirm(){
    this.$refs['elForm'].validate(valid =>{
      if(!valid){
        return;
      }
      //判断信息是否改变
      if(this.oldUser.sex !== this.user.sex 
        || this.oldUser.status !== this.user.status
        || this.oldUser.birth !== this.user.birth
        || this.oldUser.nickname !== this.user.nickname
        || this.oldUser.phoneNumber !== this.user.phoneNumber){
          this.updateUser()
        }else{
          this.$message.error('信息未修改,没有修改')
        }
    })
  },
  //修改密码
  handlePassWordConfirm(){
    this.$refs['form'].validate(valid =>{
      if(!valid){
        return
      }
      this.updatePassword()
    })
  },
  async updatePassword(){
    const res = await updateUserPassWord(this.userPassword.oldPassword,this.userPassword.confirmPassword)
    console.log(res)
    if(res.code == 200){
     this.$notify.success({
        title:'操作成功',
        message: '密码修改成功',
      })
    }else{
      
    }
  }
}
  
}
</script>
<style  lang="less" scoped>
  .list-group {
    padding-left: 0;
    list-style: none;
  }

  .list-group-item {
    border-bottom: 1px solid #e7eaec;
    border-top: 1px solid #e7eaec;
    margin-bottom: -1px;
    padding: 11px 0;
    font-size: 13px;
  }

  .pull-right {
    float: right !important;
  }

  .text-center {
    text-align: center
  }

  .user-info-head {
    position: relative;
    display: inline-block;
    height: 120px;
  }

  .user-info-head:hover:after {
    content: '+';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    color: #eee;
    background: rgba(0, 0, 0, 0.5);
    font-size: 24px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    cursor: pointer;
    line-height: 110px;
    border-radius: 50%;
  }

  /* image */
  .img-circle {
    border-radius: 50%;
  }

  .img-lg {
    width: 120px;
    height: 120px;
  }
</style>